// pages/seal/orderDetail/orderDetail.js
import config from '../../../utils/config';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderDetail: null,
    loading: true,
    error: '',
    rating: 0,
    comment: '',
    showReviewButton: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('orderDetail onLoad options:', options);
    const orderId = options.orderId;
    console.log('orderId:', orderId);
    if (!orderId) {
      this.setData({ error: '缺少订单ID', loading: false });
      return;
    }
    this.fetchOrderDetail(orderId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  handleCopyOrderNo(e) {
    const orderNo = e.currentTarget.dataset.orderno;
    if (orderNo) {
      wx.setClipboardData({
        data: orderNo,
        success: () => {
          wx.showToast({ title: '订单号已复制', icon: 'none' });
        },
        fail: () => {
          wx.showToast({ title: '复制失败', icon: 'none' });
        }
      });
    }
  },

  handleUpload() {
    // 跳转到上传资料页面，带上当前订单ID
    if (this.data.orderDetail && this.data.orderDetail.id) {
      wx.navigateTo({
        url: `/pages/seal/fileUpload/fileUpload?orderId=${this.data.orderDetail.id}`
      });
    } else {
      wx.showToast({ title: '订单信息缺失', icon: 'none' });
    }
  },

  // 查看物流
  handleViewLogistics() {
    if (this.data.orderDetail && this.data.orderDetail.courierNo) {
      // 跳转到物流页面
      wx.navigateTo({
        url: `/pages/seal/logistics/logistics?courierNo=${encodeURIComponent(this.data.orderDetail.courierNo)}&orderNo=${encodeURIComponent(this.data.orderDetail.orderNo || '')}`
      });
    } else {
      wx.showToast({
        title: '暂无物流信息',
        icon: 'none',
        duration: 1500
      });
    }
  },
  handleGoHome() {
    wx.reLaunch({ url: '/pages/profile/profile' });
  },

  // 预览备案回执图片
  handlePreviewBeian(e) {
    try {
      const datasetUrl = e && e.currentTarget && e.currentTarget.dataset ? e.currentTarget.dataset.url : '';
      const beianField = datasetUrl || (this.data.orderDetail ? this.data.orderDetail.beian : '');
      if (!beianField) {
        wx.showToast({ title: '暂无回执图片', icon: 'none' });
        return;
      }
      const urls = Array.isArray(beianField) ? beianField : [beianField];
      wx.previewImage({
        current: urls[0],
        urls
      });
    } catch (err) {
      wx.showToast({ title: '预览失败', icon: 'none' });
    }
  },

  fetchOrderDetail(orderId) {
    console.log('fetchOrderDetail orderId:', orderId);
    
    const token = wx.getStorageSync('token');
    this.setData({ loading: true, error: '' });
    wx.request({
      url: `${config.baseUrl}/seal/getOrderDetail/${orderId}`,
      method: 'GET',
      header: {
        'Authorization': token
      },
      success: (res) => {
        if (res.data && res.data.code === 200 && res.data.data && res.data.data.orderDetail) {
          const detail = res.data.data.orderDetail;
          const mappedDetail = {
            ...detail,
            statusClass: this.mapStatusToClass(detail.status),
            statusText: this.mapStatusToText(detail.status)
          };
          // 判断是否显示评价按钮：已完成状态且没有评价时，不显示评价按钮（因为会显示评价输入模块）
          const showReviewButton = !(mappedDetail.status === 6 && (!mappedDetail.evaluates || mappedDetail.evaluates.length === 0));
          
          this.setData({ 
            orderDetail: mappedDetail, 
            loading: false,
            showReviewButton: showReviewButton
          });
        } else {
          this.setData({ error: res.data.msg || '获取订单详情失败', loading: false });
        }
      },
      fail: () => {
        this.setData({ error: '网络错误', loading: false });
      }
    });
  },

  // 将后端数值状态映射为样式类和文本
  mapStatusToClass(statusCode) {
    switch (statusCode) {
      case 0: // 待付款
        return 'status-warning';
      case 1: // 待处理
        return 'status-info';
      case 2: // 处理中
        return 'status-primary';
      case 3: // 提交备案
        return 'status-secondary';
      case 4: // 已发货
        return 'status-success';
      case 5: // 退款/售后
        return 'status-danger';
      case 6: // 已完成
        return 'status-finish';
      default:
        return 'status-secondary';
    }
  },

  // 将后端数值状态映射为状态文本
  mapStatusToText(statusCode) {
    switch (statusCode) {
      case 0:
        return '待付款';
      case 1:
        return '待处理';
      case 2:
        return '处理中';
      case 3:
        return '提交备案';
      case 4:
        return '已发货';
      case 5:
        return '退款/售后';
      case 6:
        return '已完成';
      default:
        return '未知状态';
    }
  },

  // 设置评分
  setRating(e) {
    const rating = e.currentTarget.dataset.rating;
    this.setData({
      rating: rating
    });
  },

  // 评价内容输入
  onCommentInput(e) {
    this.setData({
      comment: e.detail.value
    });
  },

  // 提交评价
  submitReview() {
    if (this.data.rating === 0) {
      wx.showToast({
        title: '请选择评分',
        icon: 'none'
      });
      return;
    }

    if (!this.data.comment.trim()) {
      wx.showToast({
        title: '请输入评价内容',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '提交中...'
    });

    const token = wx.getStorageSync('token');
    wx.request({
      url: `${config.baseUrl}/seal/submitReview`,
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        orderId: this.data.orderDetail.id,
        rating: this.data.rating,
        comment: this.data.comment
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data && res.data.code === 200) {
          wx.showToast({
            title: '评价提交成功',
            icon: 'success'
          });
          
          // 更新订单详情，添加评价到evaluates数组
          const orderDetail = { ...this.data.orderDetail };
          if (!orderDetail.evaluates) {
            orderDetail.evaluates = [];
          }
          orderDetail.evaluates.push({
            rating: this.data.rating,
            comment: this.data.comment
          });
          
          // 评价提交成功后，更新showReviewButton状态
          const showReviewButton = !(orderDetail.status === 6 && (!orderDetail.evaluates || orderDetail.evaluates.length === 0));
          
          this.setData({
            orderDetail: orderDetail,
            rating: 0,
            comment: '',
            showReviewButton: showReviewButton
          });
        } else {
          wx.showToast({
            title: res.data.msg || '评价提交失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 显示评价模块
  goToReview() {
    // 由于评价输入模块已经通过条件渲染显示，这个方法主要用于其他状态下的评价入口
    // 如果需要在其他状态下显示评价模块，可以在这里添加逻辑
    wx.showToast({
      title: '请填写评价信息',
      icon: 'none'
    });
  },

  // 立即付款
  handlePay() {
    const orderDetail = this.data.orderDetail;
    if (!orderDetail) {
      wx.showToast({
        title: '订单信息错误',
        icon: 'error'
      });
      return;
    }

    // 跳转到订单页面进行支付
    wx.navigateTo({
      url: `/pages/seal/order/order?orderId=${orderDetail.id}&price=${orderDetail.payPrice}`
    });
  }
})